package com.ccjk.beusoft.hot

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import dalvik.system.DexClassLoader
import java.io.File
import java.lang.reflect.Constructor

class ProxyActivity : AppCompatActivity() {

    companion object {
        val FROM = "FROM"
        val INTERNAL = 1
        val EXTERNAL = 2
        fun start(context: Context, apkPath: String) {
            context.startActivity(Intent(context, ProxyActivity::class.java)
                    .putExtra("apkPath", apkPath)
            )
        }
    }

    var apkPath = ""
    private lateinit var dexOutDir: File
    //
    private var targetActivityClassName = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        apkPath = intent.getStringExtra("apkPath");
        dexOutDir = File(cacheDir, "dex")
        if (!dexOutDir.isDirectory) {
            dexOutDir.mkdirs()
        }
        startTargetPlugin();


    }

    lateinit var a: String;
    lateinit var progressListener: ((task: Int, progress: Int) -> Unit)
    lateinit var callback: (() -> Unit)

    fun startTargetPlugin() {
        val packageInfo: PackageInfo = packageManager.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        packageInfo.activities?.let {
            if (it.size > 0) {
                targetActivityClassName = it[0].name
            }
        }
        //
        val classLoader = ClassLoader.getSystemClassLoader();
        val dexClassLoader: DexClassLoader = DexClassLoader(apkPath, dexOutDir.absolutePath, null, classLoader);
        val targetActivityClass = dexClassLoader.loadClass(targetActivityClassName)
        Util.start(dexClassLoader, apkPath, targetActivityClass, targetActivityClassName, this)


    }


}

